package com.juc;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tgy
 * @Date: 2020-07-27 15:59
 */

class CyclicBarrierData{

    private CyclicBarrier cyclicBarrier;

    public CyclicBarrierData(int parties){

        this.cyclicBarrier = new CyclicBarrier(parties,()->{

            System.out.println("执行");
            this.cyclicBarrier.reset();
        });
    }

    public void run(){


        for (int i = 0; i < 100; i++){

            final int j = i;
            new Thread(()->{

                try {

                    System.out.println("await before index = " + j);
                    TimeUnit.SECONDS.sleep(2);
                    this.cyclicBarrier.await();
                    System.out.println("await after index = " + j);
                }catch (Exception e){

                }

            }).start();
        }


    }


}

public class CyclicBarrierTest {

    public static void main(String[] args) {


        CyclicBarrierData cyclicBarrierData = new CyclicBarrierData(10);

        cyclicBarrierData.run();

        while (Thread.activeCount() > 2){

            Thread.yield();
        }
    }

    public static void test01(){
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10,()->{

            //开会
            System.out.println("开会...");
        });




        for (int i = 0; i < 10; i++) {

            final int j = i;
            new Thread(()->{


                try {

                    System.out.println("index" + j);
                    TimeUnit.SECONDS.sleep(2);
                    cyclicBarrier.await();

                    System.out.println("sadas " + j);
                }catch (Exception e){

                }

            }).start();
        }
    }
}
